package vehicle

import (
	"fmt"
	"gitee.com/watertreestar/octans-device-sdk/internal"
	"strings"
	"time"
)

type Header struct {
	Magic []byte `struc:"[4]byte"`
	SN    uint32 `struc:"uint32,little"`
}

func (d Header) SNString() string {
	return fmt.Sprintf("%02X", d.SN)
}

type DiscoveryResponse struct {
	Header
	IP      []uint8 `struc:"[4]uint8"`
	Mask    []uint8 `struc:"[4]uint8"`
	Gateway []uint8 `struc:"[4]uint8"`
	Mac     []byte  `struct:"[6]byte"`
}

func (d DiscoveryResponse) MacString() string {
	var mac = make([]string, len(d.Mac))
	for i := range d.Mac {
		mac[i] = strings.ToUpper(fmt.Sprintf("%02x", d.Mac[i]))
	}
	return strings.Join(mac, ":")
}

func (d DiscoveryResponse) IPString() string {
	return fmt.Sprintf("%d.%d.%d.%d", d.IP[0], d.IP[1], d.IP[2], d.IP[3])
}

type RecordResponse struct {
	Header
	RecordIndex uint   `struc:"uint32"`
	RecordType  uint8  `struc:"uint8"`
	Pass        uint8  `struc:"uint8"`
	DoorNum     uint8  `struc:"uint8"`
	Direction   uint8  `struc:"uint8"`
	CardNum     uint32 `struc:"uint32,little"`
	Date        []byte `struc:"[7]byte"`
}

type StatusResponse struct {
	Header
	LastIndex  uint8  `struc:"uint8"`
	RecordType uint8  `stuc:"uint8"`
	Pass       uint8  `struc:"uint8"`
	DoorNum    uint8  `struc:"uint8"`
	Direction  uint8  `struc:"uint8"`
	CardNum    uint   `struc:"uint32,little"`
	Date       []byte `struc:"[7]byte"`
}

type SwipeData struct {
	SN        string `json:"sn"`
	Pass      uint8  `json:"pass"`
	DoorNum   uint8  `json:"door_num"`
	Direction uint8  `json:"direction"`
	CarNum    uint32 `json:"car_num"`
}

func (sd SwipeData) String() string {
	return fmt.Sprintf("卡%d触发%d号门事件,方向:%d,是否通过:%d, "+
		"控制器序列号:%s", sd.CarNum, sd.DoorNum,
		sd.Direction, sd.Pass, sd.SN,
	)
}

type probeStatusPacket struct {
	Header
	Pad []byte `struc:"[56]pad"`
}

type UploadPrivilegePacket struct {
	Header
	CardNum   uint32  `struc:"uint32,little"`
	StartDate []uint8 `struc:"[4]uint8"`
	EndDate   []uint8 `struc:"[4]uint8"`
	DoorOne   bool    `struc:"bool"`
	DoorTwo   bool    `struc:"bool"`
	DoorThree bool    `struc:"bool"`
	DoorFour  bool    `struc:"bool"`
	Pad       []byte  `struc:"[40]pad"`
}

func (u *UploadPrivilegePacket) permitAll() {
	u.DoorOne = true
	u.DoorTwo = true
	u.DoorThree = true
	u.DoorFour = true
	t := time.Now()
	year := uint8(t.Year() - 2000)
	mon := uint8(t.Month())
	day := uint8(t.Day())
	u.StartDate = []byte{
		internal.BCD(20), internal.BCD(year),
		internal.BCD(mon), internal.BCD(day),
	}
	u.EndDate = []byte{
		internal.BCD(20), internal.BCD(29),
		internal.BCD(12), internal.BCD(31),
	}
}

type RemovePrivilegePacket struct {
	Header
	CardNum uint32 `struc:"uint32,little"`
	Pad     []byte `struc:"[52]pad"`
}

type ClearPrivilegePacket struct {
	Header
	Flag []byte `struc:"[4]byte"`
	Pad  []byte `struc:"[52]pad"`
}
